import huck
import huck.api.session
import beaker.middleware

class Session(huck.api.session.Abstract):

  def __init__(self, handler, type):
    super(Session, self).__init__(handler, type)
    self.__session = self.handler.request.environ['huck.session.%s' % self.type]

  def delete(self, key):
    try:
      del self.__session[key]
    except KeyError:
      pass

  def get(self, key, default=None):
    try:
      return self.__session[key]
    except KeyError:
      return default

  def set(self, key, value):
    self.__session[key] = value

  def save(self):
    self.__session.save()

class Create(object):

  def __init__(self, options=None, type='default'):
    self.options = options or {}
    self.type = type
    if not 'session.id' in self.options:
      self.options['session.id'] = 'session.%s.id' % self.type

  def setup(self, application):
    huck.api.session.set(Session, self.type)
    return beaker.middleware.SessionMiddleware(application, self.options, environ_key='huck.session.%s' % self.type)
